#include "db_mysql.h"


MYSQL* g_conn=NULL;
//保存DHT11上报数据
int DHT11SaveData(int argc,char *argv[])
{
    if (g_conn == NULL) {
        printf("错误：数据库连接未初始化\n");
        return SYS_ERROR;
    }
    int device_id = atoi(argv[1]);
    int device_type = atoi(argv[2]);
    double humidity = atof(argv[3]);
    double temperature = atof(argv[4]);

    char sql[512]="";
    snprintf(sql,sizeof(sql),
            "insert into dht11_data_record (device_id,device_type,humidity,temperature,record_time) values(%d,%d,%.1f,%.1f,now())",device_id,device_type,humidity,temperature);

    if(mysql_query(g_conn,sql)!=0)
    {
        printf("数据保存失败\n");
        return SYS_ERROR;
    }
    return SYS_OK;
}
//初始化数据库
int InitMysql()
{
    g_conn = mysql_init(NULL);
    if (g_conn == NULL) {
        printf("初始化MySQL连接失败\n");
        return SYS_ERROR;
    }
    if(mysql_real_connect(g_conn,"127.0.0.1","root","123456","dht11",0,NULL,0))
    {
        printf("数据库连接成功\n");
    }
    else
    {

        printf("数据库连接失败\n");
        mysql_close(g_conn);
        g_conn = NULL;
        return SYS_ERROR;
    }

}
//关闭数据库
int CloseMysql()
{
    if (g_conn != NULL) {
        mysql_close(g_conn);
        g_conn = NULL;
        printf("数据库连接已关闭\n");
    }
    return SYS_OK;
    //mysql_close(g_conn);
}


